<template>
  <view class="u-page">
	  <u-navbar
	    :left-title="title"
	    
	    left-icon="arrow-left"
	    left-icon-color="#303133"
	    bg-color="#ffffff"
	    fixed
	    placeholder
	    @left-click="back"
	  />
    <!-- 顶部标题栏 -->
    

    <!-- 内容容器 -->
    <view class="content-container">
      <view class="content">

        <!-- 薪资明细 -->
        <view class="salary-details">
          <!-- 员工信息 -->
          <view class="employee-info">
            <text class="employee-name">{{ salaryData.name }}</text>
			<text class="employee-job">{{ salaryData.jobname }}</text>
            <text class="date">{{ salaryData.passGtm }}</text>
          </view>
          <view class="custom-description">
            <view class="description-row">
              <text class="description-label">发放月份</text>
              <text class="description-value">{{ monthFormat(salaryData.month) }}</text>
            </view>
            <view class="description-row">
              <text class="description-label">基本工资</text>
              <text class="description-value">{{ salaryData.baseSalary }}</text>
            </view>
            <view class="description-row">
              <text class="description-label">奖金</text>
              <text class="description-value">{{ salaryData.award }}</text>
            </view>
            <view class="description-row">
              <text class="description-label">补贴</text>
              <text class="description-value">{{ salaryData.allowance }}</text>
            </view>
          </view>
        </view>

        <view class="salary-details">
          <view class="custom-description">
            <view class="description-row">
              <text class="description-label">本人缴纳社会保险</text>
              <text class="description-value">{{ salaryData.personPay }}</text>
            </view>
            <view class="description-row">
              <text class="description-label">单位缴纳社会保险</text>
              <text class="description-value">{{ salaryData.companyPay }}</text>
            </view>
          </view>
        </view>

        <view class="salary-details">
          <view class="custom-description">
            <view class="description-row">
              <text class="description-label">加班费</text>
              <text class="description-value">{{ salaryData.overtimePay }}</text>
            </view>
            <view class="description-row">
              <text class="description-label">绩效</text>
              <text class="description-value">{{ salaryData.performance }}</text>
            </view>
            <view class="description-row">
              <text class="description-label">本月工资</text>
              <text class="description-value">{{ parseInt(salaryData.realSalary) }}</text>
            </view>
          </view>
        </view>

        <!-- 异议进度模块 -->
        <view class="salary-details" v-if="progressItems.length > 0">
          <view class="progress-title">进度</view>
          <view class="progress-content">
            <view class="progress-item" v-for="(item, index) in progressItems" :key="index">
              <view class="progress-line" v-if="index < progressItems.length - 1"
                :class="{ 'active-line': index == progressItems.length - 2 }"></view>
              <view class="progress-dot" :class="{ 'active-dot': index == progressItems.length - 1 }"></view>
              <view class="progress-info">
                <text class="progress-status" :class="{ 'active-status': index == progressItems.length - 1 }">{{
                  getStateTitle(item) }}</text>
                <text class="progress-content-text">{{ item.content }}</text>
                <text class="progress-time">{{ item.createGtm }}</text>
                <view class="buttons" style="margin-top: 20px;width:50vw"
                  v-if="item.state === '4' && item.sourceType == '1' && index == progressItems.length - 1">
                  <up-button type="default" class="dispute-btn" @click="showDisputePopup = true">提出异议</up-button>
                  <up-button type="primary" class="confirm-btn" @click="show5 = true">确认无误</up-button>
                </view>
              </view>
            </view>
          </view>
        </view>

      </view>
    </view>

    <!-- 底部按钮区域 - 固定显示 -->
    <view class="bottom-actions">
      <text class="total-amount-label">实发：</text>
      <text class="total-amount-value">{{ parseInt(salaryData.realSalary) - parseInt(salaryData.personPay) }}</text>
      <view class="buttons" v-if="salaryData.state == '2'">
        <up-button type="default" class="dispute-btn" @click="showDisputePopup = true">提出异议</up-button>
        <up-button type="primary" class="confirm-btn" @click="show5 = true">确认无误</up-button>
      </view>
      <view class="buttons" v-if="salaryData.state != '2'">
        
      </view>
    </view>
  </view>
  <up-modal :content="content" :show="show5" showCancelButton cancelText="再看看" contentTextAlign="center"
    cancelColor="#000" @confirm="confirmSalary" @cancel="() => show5 = false"></up-modal>

  <up-popup :show="showDisputePopup" mode="center" @close="showDisputePopup = false">
    <view class="dispute-popup-content">
      <view class="popup-header">
        <text class="popup-title">提出异议</text>
        <u-icon name="close" size="20" @click="showDisputePopup = false" class="close-icon" />
      </view>
      <view class="popup-body">
        <text class="form-label">异议内容</text>
        <textarea :v-model="disputeContent" class="dispute-textarea" placeholder="请输入"
          placeholder-class="textarea-placeholder" @input="handleDisputeInput" maxlength="100"></textarea>
        <text class="char-count">{{ disputeContent.length }}/100</text>
        <text v-if="showError" class="error-tip">请输入异议内容</text>
      </view>
      <view class="popup-footer">
        <up-button type="primary" class="submit-btn" @click="submitDispute">确定</up-button>
      </view>
    </view>
  </up-popup>
</template>

<script setup>
import { ref } from 'vue';
// 使用ES模块导入语法
import { navigate as publicNavigate } from '@/utils/public.js';
import { getById, setState } from '../../api/salary';
import { getListByVo  } from '../../api/opinion';
const title = ref('工资详情');
const content = ref('工资是否确认无误？');
const show5 = ref(false);
const showDisputePopup = ref(false);
const disputeContent = ref('');
const showError = ref(false);
// 从小程序全局属性中获取页面参数
// 这种方式在小程序环境中更可靠
import { onLoad } from '@dcloudio/uni-app';

const salaryId = ref('');


// 使用onLoad生命周期函数获取路由参数
onLoad((options) => {
// #ifdef MP-WEIXIN
  console.log('onLoad获取到的参数:', options);
  // 直接从onLoad的options参数中获取id
  if (options && options.id) {
    salaryId.value = options.id;
  } else {
    console.error('未获取到工资ID参数');
    // 可以在这里添加处理逻辑，如：
    // uni.showToast({
    //   title: '参数错误，请重新进入页面',
    //   icon: 'none'
    // });
    // uni.navigateBack();
  }
  console.log('获取到的salaryId:', salaryId.value);
  loadSalaryData();
// #endif
// #ifndef MP-WEIXIN
  console.log('非微信小程序环境，使用options参数获取id');
 // 使用原来的方式获取参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  // 添加防御性检查，确保options存在且有id属性
  if (currentPage && currentPage.options && currentPage.options.id) {
    salaryId.value = currentPage.options.id;
  } else {
    console.error('未获取到工资ID参数');
  } 
  console.log('获取到的salaryId:', salaryId.value);
  loadSalaryData();
// #endif
});
const monthFormat = (month) => {
		// 确保month是字符串类型
		const monthStr = String(month);
		// 匹配完整的日期时间格式 YYYY-MM-DD HH:MM:SS
		const fullDateMatch = monthStr.match(/^(\d{4})-(\d{2})-(\d{2})/);
		if (fullDateMatch) {
			// return `${fullDateMatch[1]}年${fullDateMatch[2]}月${fullDateMatch[3]}日`;
			return `${fullDateMatch[1]}年${fullDateMatch[2]}月`;
		}
		// // 匹配年月格式 YYYY-MM
		// const yearMonthMatch = monthStr.match(/^(\d+)-(\d+)$/);
		// if (yearMonthMatch) {
		// 	return `${yearMonthMatch[1]}年${yearMonthMatch[2]}月`;
		// }
		// 返回原始值（如果都不匹配）
		return monthStr;
	};
// 处理异议内容输入
const handleDisputeInput = (e) => {
  disputeContent.value = e.detail.value;
  // 限制最多100个字符
  if (disputeContent.value.length > 100) {
    disputeContent.value = disputeContent.value.substring(0, 100);
  }
};
const getStateTitle = (item) => {
  if (item.state === '4'  && item.sourceType == '0') {
    return '提出异议';
  } else if (item.state === '2'  && item.sourceType == '1') {
    return '异议回复';
  } else if (item.state === '5') {
    return '确认无误';
  } else {
    return '-----';
  }
}
const confirmSalary = async () => {
  // 检查salaryId是否存在
  if (!salaryId.value) {
    console.error('salaryId不存在，无法确认工资');
    return;
  }
  
  const res = await setState({
    id: salaryId.value,
    state: 5
  }).catch(err => {
    console.log(err.msg)
    uni.showToast({
      title: '确认失败',
      icon: 'none'
    });
  })
  if (res) {
    if (res.code === 200) {
      uni.showToast({
        title: '确认成功',
        icon: 'none'
      });
      show5.value = false;
      loadSalaryData();
    } else {
      console.log(res.msg)
      uni.showToast({
        title: '确认失败',
        icon: 'none'
      });
    }
  } else {
    console.log(res.msg)
    uni.showToast({
      title: '确认失败',
      icon: 'none'
    });
  }
};

// 提交异议
const submitDispute = async() => {
  if (!disputeContent.value.trim()) {
    showError.value = true;
    return;
  }
  showError.value = false;
  console.log('提交异议:', disputeContent.value);
  // 这里可以添加提交异议的逻辑
  const res = await setState({
    id: salaryId.value,
    state: 4,
    description: disputeContent.value
  }).catch(err => {
    console.log(err.msg)
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    });
  }).finally(() => {
    showDisputePopup.value = false;
    disputeContent.value = '';
  })
  if (res.code == 200) {
      // progressItems.value[currentProgress.value].status = '异议回复';
      // progressItems.value[currentProgress.value].time = new Date().toLocaleString();
      // progressItems.value[currentProgress.value].content = disputeContent.value;
      // currentProgress.value++;
      uni.showToast({
        title: '完成',
        icon: 'none'
      });
      loadSalaryData();
    } else {
      console.log(res.msg)
      uni.showToast({
        title: '提交失败',
        icon: 'none'
      });
    }

};
// 异议进度数据
const progressItems = ref([
  {
    status: '提出异议',
    time: '2025-09-09 23:23',
    content: '内容xxxxxxxxxxxxxxxxxxxxxxxxxxx'
  },
  {
    status: '异议回复',
    time: '2025-09-10 23:23',
    content: '内容xxxxxxxxxxxxxxxxxxxxxxxxxxx'
  },
  //   {
  //     status: '确认无误',
  //     time: '2025-09-11 23:23',
  //     content: '内容xxxxxxxxxxxxxxxxxxxxxxxxxxx'
  //   }
]);

// 当前进度
const currentProgress = ref(2);

// 薪资明细数据
const salaryData = ref({
  month: '8月',
  basicSalary: 'xxxxxx',
  bonus: 'xxxxxx',
  subsidy: 'xxxxxx',
  personalSocialInsurance: 'xxxxxx',
  companySocialInsurance: 'xxxxxx',
  overtimePay: 'xxxxxx',
  performance: 'xxxxxx',
  monthlySalary: 'xxxxxx',
  netSalary: '10000',
  employeeName: '张三',
  position: '产品经理',
  employeeDate: '2023.09.09 21:23'
});
const loadSalaryData = async () => {
  // 检查salaryId是否存在
  if (!salaryId.value) {
    console.error('salaryId不存在，无法加载数据');
    return;
  }
  
  const res = await getById(salaryId.value).catch(err => {
    console.log(err);
  });
  if (res.code == 200) {
    console.log(res)
    salaryData.value = res.data.vo;
    console.log(salaryData.value)
  } else {
    console.log(res.msg)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
  }
  const res2 = await getListByVo({
    salaryId: salaryId.value
  }).catch(err => {
    console.log(err);
  });
  if (res2.code == 200) {
    console.log(res2)
    progressItems.value = res2.data.list;
    console.log(progressItems.value)
  } else {
    console.log(res2.msg)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
  }
}



// 返回上一页
const back = () => {
  publicNavigate('back')
};
</script>

<style scoped>
.u-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  position: relative;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.nav-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background-color: #000;
  color: #fff;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  color: #fff;
}

.content {
  padding: 0;
}

.employee-info {
  padding: 16px 16px 0;
}

.employee-name {
  font-size: 20px;
  font-weight: bolder;
  color: #000;
  margin-bottom: 5px;
}
	.employee-job {
		font-size: 15px;
		color: #4d4f51;
		background-color: #eaf1fa;
		padding: 2px 8px;
		border-radius: 4px;
		margin-left: 5px;
	}
.date {
  font-size: 14px;
  color: #000;
  display: block;
}

.month {
  font-size: 14px;
  color: #666;
  float: right;
}

.salary-details {
  background-color: #fff;
  margin: 16px 10px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.custom-description {
  padding: 0 16px;
}

.description-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
}

.description-label {
  font-size: 14px;
  color: #aaadad;
  flex: 1;
}

.description-value {
  font-size: 14px;
  color: #000;
  text-align: right;
  min-width: 100px;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.content {
  padding: 0;
  padding-bottom: 80px;
  /* 为固定底部留出空间 */
}

.total-amount-label {
  font-size: 16px;
  font-weight: bold;
  color: #000;
}

.total-amount-value {
  font-size: 16px;
  font-weight: bold;
  color: #964309;
  margin-right: 16px;
}

.buttons {
  display: flex;
  gap: 16px;
  flex: 1;
}

.dispute-btn {
  flex: 1;
  background-color: #fff;
  color: #333;
  border: 1px solid #ddd;
  height: 44px;
  border-radius: 22px;
}

.confirm-btn {
  flex: 1;
  background-color: #1989fa;
  color: #fff;
  height: 44px;
  border-radius: 22px;
}

/* 提出异议弹出层样式 */
.dispute-popup-content {
  max-width: 80vw;
  min-width: 60vw;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 16px;
  font-weight: 500;
  color: #000;
}

.close-icon {
  color: #999;
}

.popup-body {
  padding: 16px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.dispute-textarea {
  width: 100%;
  height: 120px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  background-color: #fafafa;
  resize: none;
  box-sizing: border-box;
}

.textarea-placeholder {
  color: #999;
}

.char-count {
  display: block;
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.error-tip {
  display: block;
  font-size: 12px;
  color: #f56c6c;
  margin-top: 8px;
}

.popup-footer {
  padding: 16px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #1989fa;
  color: #fff;
  border-radius: 22px;
  font-size: 16px;
}

/* 异议进度样式 */
.progress-title {
  font-size: 20px;
  font-weight: bolder;
  color: #000;
  padding: 16px 16px 0;
}

.progress-content {
  padding: 16px;
  position: relative;
}

.progress-item {
  display: flex;
  position: relative;
  margin-bottom: 20px;
}

.progress-line {
  width: 2px;
  background-color: #e0e0e0;
  position: absolute;
  left: 9px;
  top: 20px;
  bottom: -20px;
  z-index: 1;
}

.active-line {
  background-color: #1989fa;
}

.progress-dot {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
  position: relative;
  z-index: 2;
}

.active-dot {
  background-color: #1989fa;
}

.progress-info {
  flex: 1;
}

.progress-status {
  font-size: 15px;
  font-weight: bolder;
  color: #000;
  display: block;
  margin-bottom: 4px;
}

.active-status {
  color: #333;
}

.progress-time {
  font-size: 12px;
  color: #999;
  display: block;
  margin-bottom: 4px;
}

.progress-content-text {
  font-size: 14px;
  color: #666;
  display: block;
  word-break: break-all;
}
</style>